package com.huifaapp.mall.js;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.EvaluateActivity;

import com.huifaapp.mall.activity.LoginActivity;
import com.huifaapp.mall.activity.WebActivity;

import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.base.activity.BaseActivity;
import com.huifaapp.mall.base.bean.PayBean;
import com.huifaapp.mall.dialogs.ShareDialog;
import com.huifaapp.mall.uitils.AlipayUtils;
import com.just.library.AgentWeb;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tencent.mm.opensdk.modelpay.PayReq;

import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.json.JSONException;
import org.json.JSONObject;

import static com.huifaapp.mall.afinal.Constants.WX_APPID;


/**
 * @author: wangZ
 * @date：2017/8/20 11:53
 * FileName：AndroidInterface
 * description：注入到JS里的方法都卸载此类里面
 */


public class AndroidInterface {

    private Handler deliver = new Handler(Looper.getMainLooper());
    private AgentWeb mAgentWeb;
    private Context context;

    public AndroidInterface(AgentWeb agent, Context context) {
        this.mAgentWeb = agent;
        this.context = context;
    }

    /**
     * obj:暴露的要调用的对象
     * interfaceName：对象的映射名称 ,object的对象名，在js中可以直接调用
     * 在html的js中：JSTest.showToast(msg)
     * 可以直接访问JSTest，这是因为JSTest挂载到js的window对象下了
     */


    @JavascriptInterface
    public void callAndroid(final String msg) {


        deliver.post(new Runnable() {
            @Override
            public void run() {

                Log.i("Info", "main Thread:" + Thread.currentThread());
                Toast.makeText(context.getApplicationContext(), "" + msg, Toast.LENGTH_LONG).show();
            }
        });


        Log.i("Info", "Thread:" + Thread.currentThread());

    }

    @JavascriptInterface
    public void getAndroidRedRain(final String msg) {


        deliver.post(new Runnable() {
            @Override
            public void run() {

                Log.i("Info", "main Thread:" + Thread.currentThread());
                Toast.makeText(context.getApplicationContext(), "" + msg, Toast.LENGTH_LONG).show();
            }
        });


        Log.i("Info", "Thread:" + Thread.currentThread());

    }

    /**
     * 分享方法
     *
     * @param
     */
    @JavascriptInterface
    public void shareProduct(String json) {
        Log.e("SJ","shareProduct分享"+json);
        try {
            JSONObject object = new JSONObject(json);
            String status = object.optString("status");//为1时分享给朋友，2时分享到朋友圈
            String url = object.optString("url");
            String title = object.optString("title");
            String content = object.optString("content");
            final UMWeb web = new UMWeb(url);
            web.setTitle(title);//标题
//                   web.setThumb(new UMImage(context, ApiManager.BASE_IMAGE_URL+bean.getImgUrl()));  //缩略图
//            web.setThumb(new UMImage(context, url));  //缩略图
            web.setThumb(new UMImage(context, R.drawable.icon_share_log));  //缩略图
            web.setDescription(content);//描述
            shareUrl(web,status);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtils.e(json);

//        ShareDialog shareDialog = new ShareDialog(context);
//        shareDialog.show();

    }
    @JavascriptInterface
    public void addJd(){
//        if (checkPackage("com.jingdong.app.mall")) {
//            Log.e("数据", "addJd()进来");
////            String url = "https://item.jd.com/231023.html";
//            Intent intent = new Intent();
//            intent.setAction("android.intent.action.VIEW");
////            Uri uri = Uri.parse(url);
////            intent.setData(uri);
////            Intent intent = new Intent(Intent.ACTION_MAIN);
////            //知道要跳转应用的包名、类名
////            ComponentName componentName = new ComponentName("com.jingdong.app", "com.jingdong.app.mall");
////            intent.setComponent(componentName);
            // 通过包名获取要跳转的app，创建intent对象

            Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.jingdong.app.mall");
            // 这里如果intent为空，就说名没有安装要跳转的应用嘛
            if (intent != null) {

                context.startActivity(intent);

            } else {

                // 没有安装要跳转的app应用，提醒一下

                Toast.makeText(context.getApplicationContext(), "哟，赶紧下载安装这个APP吧", Toast.LENGTH_LONG).show();

            }
            context.startActivity(intent);
        }
//    }
    /**
     * 检测该包名所对应的应用是否存在
     ** @param packageName
     * @return
     */
    public boolean checkPackage(String packageName) {
        if (packageName == null || "".equals(packageName)) return false;
        try {
            //手机已安装，返回true
            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            //手机未安装，跳转到应用商店下载，并返回false
            Uri uri = Uri.parse("market://details?id="+packageName);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
            return false;
        }
    }
    /**
     * 支付方法
     *
     * @param type
     */
    @JavascriptInterface
    public void getAndroidPay(int type) {

        ShareDialog shareDialog = new ShareDialog(context);
        shareDialog.show();

    }

    /**
     * 退出登录
     */
    @JavascriptInterface
    public void loginOut() {

        SPUtils.getInstance().remove(SPConstants.KEY_USER_TOKEN);
        mAgentWeb.getJsEntraceAccess().quickCallJs("loginOut");

        deliver.postDelayed(new Runnable() {
            @Override
            public void run() {
//                ToastUtils.showShortSafe("andtaoid原生提示");
                ((BaseActivity)context).gotoActivity(LoginActivity.class,true);
            }
        }, 600);


//       ((BaseActivity)context).gotoActivity(LoginActivity.class,true);
//        CommonTowBtnDialog towBtnDialog = new CommonTowBtnDialog(context);
//
//        towBtnDialog.setContent("您确定要退出当前账号登录么?")
//                .setLeft("确定")
//                .setRight("取消")
//                .setDialogButtonOnClickListener(new CommonTowBtnDialog.DialogButtonOnClickListener() {
//                    @Override
//                    public void onLeft(View v) {
//                        ToastUtils.showShortSafe("确定");
//                    }
//
//                    @Override
//                    public void onRight(View v) {
//                        ToastUtils.showShortSafe("取消");
//                    }
//                })
//                .show();


    }

    /**
     * H5再判断Token失效的时候,调用此方法重新登录
     * 跳转到登录页面
     */
//    @JavascriptInterface
//    public void goLogin() {
//        SPUtils.getInstance().remove(SPConstants.KEY_USER_TOKEN);
//        ToastUtils.showShortSafe("token已失效,请重新登录");
//        deliver.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//
//                ((BaseActivity) context).gotoActivity(LoginActivity.class, true);
//            }
//        }, 100);
//
//
//    }

    /**
     * H5调用评价接口
     * @param json
     */
    @JavascriptInterface
    public void goEvaluate (String json) {
       LogUtils.e(json);
        try {
            JSONObject object = new JSONObject(json);

            String productId = object.optString("productId");
            String id = object.optString("id");

            Bundle bundle = new Bundle();
            bundle.putString(EvaluateActivity.KEY_PRODUCT_ID,productId);
            bundle.putString(EvaluateActivity.KEY_PINGjIA_ID,id);
            ((WebActivity)context).gotoActivity(EvaluateActivity.class,false,bundle);

        } catch (JSONException e) {
            e.printStackTrace();
        }
//

    }

    /**
     * Js调用原生的支付
     *
     * @param payType
     */
    @JavascriptInterface
    public void goPay(String payType) {
    Log.e("数据","支付==="+payType);

        String token2=SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN);
        String method = null; //支付方式 1 微信支付，2支付宝支付。
        String orderId = null;
        String token = null;
        if (TextUtils.isEmpty(payType)) {
            ToastUtils.showShortSafe("获取信息失败!");
            return;
        }
        try {
            JSONObject object = new JSONObject(payType);
            method = object.optString("method");
            orderId = object.optString("orderId");
            token = object.optString("token");
        } catch (JSONException e) {
            e.printStackTrace();
            ToastUtils.showShortSafe("获取信息失败!");
        }
        LogUtils.e(payType);
        if ("1".equals(method)) {
//            String url = ApiManager.PAY_WEIXIN+"?token="+token+"&orderId="+orderId;
//            Log.e("WEB", "路径Pay=====" + url);
//            HttpUtils http = new HttpUtils();
//            http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
//                @Override
//                public void onLoading(long total, long current, boolean isUploading) {
////                  testTextView.setText(current + "/" + total);
//                    Log.e("数据", "数据-------" + current + "/" + total);
//                }
//
//                @Override
//                public void onSuccess(ResponseInfo<String> responseInfo) {
////                    textView.setText(responseInfo.result);
//
//                    try {
//                        Log.e("数据123", "数据payd-------" + responseInfo.result);
//                        Gson gson = new Gson();
//                        PayBean list = gson.fromJson(responseInfo.result, PayBean.class);
//
//                        if(list.getCode().equals("0")) {
//
//                            IWXAPI mWxApi = WXAPIFactory.createWXAPI(context, list.getData().getAppid(), true);
//                            mWxApi.registerApp(list.getData().getAppid());
//                            PayReq req = new PayReq();
//                            req.appId = list.getData().getAppid();
//                            req.partnerId = list.getData().getMch_id();
//                            req.prepayId = list.getData().getPrepay_id();
//                            req.nonceStr = list.getData().getNonce_str();
//                            req.timeStamp = list.getData().getTimestamp();
//                            req.packageValue ="Sign=WXPay";
//                            req.sign = list.getData().getSign();
//                            //在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
//                            mWxApi.sendReq(req);
//
//                        }else{
//                            Toast.makeText(context,list.getMsg(),Toast.LENGTH_SHORT).show();
//                        }
//                    }catch (JsonSyntaxException e){
//                        Toast.makeText(context,"未知错误",Toast.LENGTH_LONG).show();
//                    }
//
//                }
//
//                @Override
//                public void onStart() {
//                }
//
//                @Override
//                public void onFailure(HttpException error, String msg) {
//                }
//            });
        } else if ("2".equals(method)) {
            new AlipayUtils(context).getAlipaySignature(orderId,token,"");
        } else {
            ToastUtils.showShortSafe("获取信息失败!");
        }

    }

    /**
     * H5再判断Token失效的时候,调用此方法重新登录
     * 跳转到登录页面
     */
    @JavascriptInterface
    public void   againLogin(String json){

        SPUtils.getInstance().remove(SPConstants.KEY_USER_TOKEN);
        ToastUtils.showShortSafe("token已失效,请重新登录");
        deliver.postDelayed(new Runnable() {
            @Override
            public void run() {

                ((BaseActivity) context).gotoActivity(LoginActivity.class, true);
            }
        }, 100);

    }


    /**
     * 分享链接
     */

    private  void  shareUrl(UMWeb web, String type ){
        UMShareListener umShareListener = new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
//                if (dialog!=null&&!dialog.isShowing()) {
//                    dialog.show();
//                }
            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                if (share_media == SHARE_MEDIA.WEIXIN) {
                    ToastUtils.showShortSafe("微信分享成功");

                } else if (share_media == SHARE_MEDIA.WEIXIN_CIRCLE) {
                    ToastUtils.showShortSafe("朋友圈分享成功");
                } else {
                    ToastUtils.showShortSafe("分享成功");

                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                if (share_media == SHARE_MEDIA.WEIXIN) {
                    ToastUtils.showShortSafe("微信分享失败");

                } else if (share_media == SHARE_MEDIA.WEIXIN_CIRCLE) {
                    ToastUtils.showShortSafe("朋友圈分享失败");
                } else {
                    ToastUtils.showShortSafe("分享失败");

                }
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                if (share_media == SHARE_MEDIA.WEIXIN) {
                    ToastUtils.showShortSafe("微信分享取消");

                } else if (share_media == SHARE_MEDIA.WEIXIN_CIRCLE) {
                    ToastUtils.showShortSafe("朋友圈分享取消");
                } else {
                    ToastUtils.showShortSafe("分享取消");

                }
            }
        };



        if ("1".equals(type)) {  //分享微信
            new ShareAction((Activity) context)
                    .setPlatform(SHARE_MEDIA.WEIXIN).
                    setCallback(umShareListener)
                    .withMedia(web)
                    .share();

        } else if ("2".equals(type)) { //分享朋友圈

            new ShareAction((Activity) context).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).
                    setCallback(umShareListener)
                    .withMedia(web)
                    .share();

        }



    }

}
